package com.css.fxfzypg.modules.maps.service.impl;

import cn.afterturn.easypoi.excel.annotation.Excel;
import com.alibaba.fastjson.JSONObject;
import com.css.fxfzypg.common.utils.AreaBoundaryUtil;
import com.css.fxfzypg.constants.FxfzConstants;
import com.css.fxfzypg.modules.baseData.entity.AreaEntity;
import com.css.fxfzypg.modules.baseData.queryParams.AreaQueryParams;
import com.css.fxfzypg.modules.maps.queryParams.MapQueryParams;
import com.css.fxfzypg.modules.maps.service.AreaMapService;
import com.css.fxfzypg.modules.qhmapfiles.repository.QhMapFilesImport;
import com.css.fxfzypg.modules.qhmapfiles.repository.QhMapFilesNativeRepository;
import com.css.fxfzypg.modules.qhmapfiles.repository.entity.QhMapFilesEntity;
import com.css.fxfzypg.modules.qhmapfiles.viewobjects.QhMapFilesQueryParams;
import com.css.fxfzypg.modules.spatialData.repository.BoundaryNativeRepository;
import com.css.fxfzypg.util.CreateGson;
import com.css.fxfzypg.util.PlatformDateUtils;
import com.css.fxfzypg.util.PlatformObjectUtils;
import com.css.fxfzypg.util.UUIDGenerator;
import com.css.fxfzypg.web.PlatformSessionContext;
import com.css.fxfzypg.zcpt.sys.entity.SUser;
import com.css.fxfzypg.zcpt.sys.service.SUserService;
import com.css.fxfzypg.zcpt.sys.service.SysAreaService;
import com.css.fxfzypg.zcpt.sys.service.SysRoleService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.geotools.data.FileDataStore;
import org.geotools.data.FileDataStoreFinder;
import org.geotools.data.shapefile.ShapefileDataStore;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.data.simple.SimpleFeatureIterator;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.geometry.jts.JTS;
import org.geotools.geometry.jts.JTSFactoryFinder;
import org.geotools.referencing.CRS;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.io.ParseException;
import org.locationtech.jts.io.WKTReader;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.filter.Filter;
import org.opengis.referencing.FactoryException;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.opengis.referencing.operation.MathTransform;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSourceUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Author zyt
 * @Date: 2022/10/04
 */
@Service
@Slf4j
public class AreaMapServiceImpl implements AreaMapService {
    @Autowired
    private QhMapFilesImport qhMapFilesImport;//上传文件管理
    @Autowired
    private QhMapFilesNativeRepository qhMapFilesNativeRepository;
    @Resource
    JdbcTemplate jdbcTemplate;
    @Resource
    NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    @Autowired
    SysRoleService sysRoleService;

    @Autowired
    SUserService sUserService;

    @Autowired
    SysAreaService sysAreaService;

    /*文件查询*/
    @Override
    public Map<String, Object> getAllFile(MapQueryParams queryParams) {
        StringBuilder sql = new StringBuilder(" select * from qh_map_files ");

        StringBuilder orderSql = new StringBuilder(" order by create_time");

        StringBuilder whereSql = new StringBuilder(" where is_delete = '0'");
        StringBuilder str = new StringBuilder("");
        String userId = PlatformSessionContext.getUserID();
        String user = sUserService.getSUser(userId);
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        String role = sysRoleService.getRoleByUserId(userId);
        List<Map> roleMaps = JSONObject.parseArray(role, Map.class);
        for (Map roleMap : roleMaps) {
            str.append(roleMap.get("roleCode") + ",");
        }
        String roles = str.toString();
        if (roles.contains(FxfzConstants.YPG_PRI_YW_ROLE) || roles.contains(FxfzConstants.YPG_PRI_GL_ROLE) && !roles.contains(FxfzConstants.YPG_COUN_GL_ROLE) && !roles.contains(FxfzConstants.YPG_COUN_YW_ROLE)) {
            String province = sysAreaService.getAreaNameByAreaId(sUser.getProvinceId());
            whereSql.append(" and province = '" + province + "'");
        }
        //查询条件
        if (!PlatformObjectUtils.isEmpty(queryParams.getProvince())) {
            whereSql.append(" and province like '%" + queryParams.getProvince() + "%'");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getCity())) {
            whereSql.append(" and city like '%" + queryParams.getCity() + "%'");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getArea())) {
            whereSql.append(" and area like '%" + queryParams.getArea() + "%'");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getType())) {
            whereSql.append(" and type like '%" + queryParams.getType() + "%'");
        }

        sql.append(whereSql).append(orderSql).toString();
        Integer total = jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<>(QhMapFilesEntity.class)).size();
        //不分页，全部查询
        List<QhMapFilesEntity> files = jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<>(QhMapFilesEntity.class));
        Map<String, Object> map = new HashMap();
        map.put("total", total);
        map.put("rows", files);
        return map;
    }

    /*数据模糊全查询*/
    @Override
    public Map<String, Object> getAllData(AreaQueryParams queryParams) {
        StringBuilder sql = new StringBuilder(" select *,ST_AsText(geom) geomText from data_area ");

        StringBuilder orderSql = new StringBuilder(" order by fileuuid");

        StringBuilder whereSql = new StringBuilder(" where is_delete = '0'");

        StringBuilder str = new StringBuilder("");
        String userId = PlatformSessionContext.getUserID();
        String user = sUserService.getSUser(userId);
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        String role = sysRoleService.getRoleByUserId(userId);
        List<Map> roleMaps = JSONObject.parseArray(role, Map.class);
        for (Map roleMap : roleMaps) {
            str.append(roleMap.get("roleCode") + ",");
        }
        String roles = str.toString();
        if (roles.contains(FxfzConstants.YPG_PRI_YW_ROLE) || roles.contains(FxfzConstants.YPG_PRI_GL_ROLE) && !roles.contains(FxfzConstants.YPG_COUN_GL_ROLE) && !roles.contains(FxfzConstants.YPG_COUN_YW_ROLE)) {
            String province = sysAreaService.getAreaNameByAreaId(sUser.getProvinceId());
            whereSql.append(" and province = '" + province + "'");
        }

        //查询条件
        if (!PlatformObjectUtils.isEmpty(queryParams.getUuid())) {
            whereSql.append(" and area_id='" + queryParams.getUuid() + "'");
        }
        /*if (!PlatformObjectUtils.isEmpty(queryParams.getProvince()) ){
            whereSql.append(" and province like '%" + queryParams.getProvince() + "%'");
        }*/
        if (!PlatformObjectUtils.isEmpty(queryParams.getProvince())) {
            String province = queryParams.getProvince();
            String provinceSql = " and province like '%" + province + "%'";
            if (province.indexOf(";") != -1) {//多个省用;间隔
                String[] provinceArr = province.split(";");
                provinceSql = "";
                for (int i = 0; i < provinceArr.length; i++) {
                    if (!PlatformObjectUtils.isEmpty(provinceArr[i])) {
                        if (!PlatformObjectUtils.isEmpty(provinceSql)) {
                            provinceSql += ",";
                        }
                        provinceSql += "'" + provinceArr[i] + "'";
                    }
                }
                provinceSql = " and province in (" + provinceSql + ")";
            }
            whereSql.append(provinceSql);
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getCity())) {
            whereSql.append(" and city like '%" + queryParams.getCity() + "%'");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getCounty())) {
            whereSql.append(" and county like '%" + queryParams.getCounty() + "%'");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getFileuuid())) {
            whereSql.append(" and fileuuid='" + queryParams.getFileuuid() + "'");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getStreet())) {
            whereSql.append(" and street like '%" + queryParams.getStreet() + "%'");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getVillage())) {
            whereSql.append(" and village like '%" + queryParams.getVillage() + "%'");
        }

        //int firstIndex=(queryParams.getCurPage()-1) * queryParams.getPageSize();
        //int lastIndex=queryParams.getCurPage() * queryParams.getPageSize();
        sql.append(whereSql).append(orderSql).toString();
        //StringBuilder limitSql = new StringBuilder(" limit "+lastIndex+" offset "+ firstIndex);
        Integer total = jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<>(AreaEntity.class)).size();
        //不分页，全部查询
        List<AreaEntity> datas = jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<>(AreaEntity.class));
        Map<String, Object> map = new HashMap();
        map.put("total", total);
        map.put("rows", datas);
        return map;
    }

    /*数据数量查询*/
    @Override
    public int getAllDataCount(AreaQueryParams queryParams) {
        StringBuilder sql = new StringBuilder(" select *,ST_AsText(geom) geomText from data_area ");

        StringBuilder orderSql = new StringBuilder(" order by fileuuid");

        StringBuilder whereSql = new StringBuilder(" where is_delete = '0'");

        StringBuilder str = new StringBuilder("");
        String userId = PlatformSessionContext.getUserID();
        String user = sUserService.getSUser(userId);
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        String role = sysRoleService.getRoleByUserId(userId);
        List<Map> roleMaps = JSONObject.parseArray(role, Map.class);
        for (Map roleMap : roleMaps) {
            str.append(roleMap.get("roleCode") + ",");
        }
        String roles = str.toString();
        if (roles.contains(FxfzConstants.YPG_PRI_YW_ROLE) || roles.contains(FxfzConstants.YPG_PRI_GL_ROLE) && !roles.contains(FxfzConstants.YPG_COUN_GL_ROLE) && !roles.contains(FxfzConstants.YPG_COUN_YW_ROLE)) {
            String province = sysAreaService.getAreaNameByAreaId(sUser.getProvinceId());
            whereSql.append(" and province = '" + province + "'");
        }

        //查询条件
        if (!PlatformObjectUtils.isEmpty(queryParams.getUuid())) {
            whereSql.append(" and area_id='" + queryParams.getUuid() + "'");
        }
        /*if (!PlatformObjectUtils.isEmpty(queryParams.getProvince()) ){
            whereSql.append(" and province like '%" + queryParams.getProvince() + "%'");
        }*/
        if (!PlatformObjectUtils.isEmpty(queryParams.getProvince())) {
            String province = queryParams.getProvince();
            String provinceSql = " and province like '%" + province + "%'";
            if (province.indexOf(";") != -1) {//多个省用;间隔
                String[] provinceArr = province.split(";");
                provinceSql = "";
                for (int i = 0; i < provinceArr.length; i++) {
                    if (!PlatformObjectUtils.isEmpty(provinceArr[i])) {
                        if (!PlatformObjectUtils.isEmpty(provinceSql)) {
                            provinceSql += ",";
                        }
                        provinceSql += "'" + provinceArr[i] + "'";
                    }
                }
                provinceSql = " and province in (" + provinceSql + ")";
            }
            whereSql.append(provinceSql);
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getCity())) {
            whereSql.append(" and city like '%" + queryParams.getCity() + "%'");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getCounty())) {
            whereSql.append(" and county like '%" + queryParams.getCounty() + "%'");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getFileuuid())) {
            whereSql.append(" and fileuuid='" + queryParams.getFileuuid() + "'");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getStreet())) {
            whereSql.append(" and street like '%" + queryParams.getStreet() + "%'");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getVillage())) {
            whereSql.append(" and village like '%" + queryParams.getVillage() + "%'");
        }

        sql.append(whereSql).append(orderSql).toString();
        int total = jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<>(AreaEntity.class)).size();

        return total;
    }

    /*根据ID查询数据*/
    @Override
    public Map<String, Object> getDataById(String id) {
        StringBuilder sql = new StringBuilder(" select *,ST_AsText(geom) geomText from data_area ");

        StringBuilder orderSql = new StringBuilder(" order by fileuuid");

        StringBuilder whereSql = new StringBuilder(" where is_delete = '0'");

        //查询条件
        if (!PlatformObjectUtils.isEmpty(id)) {
            whereSql.append(" and area_id='" + id + "'");
        }
        sql.append(whereSql).append(orderSql).toString();
        List<AreaEntity> datas = jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<>(AreaEntity.class));
        Map<String, Object> map = new HashMap();
        map.put("rows", datas);
        return map;
    }

    /*逻辑删除文件及相关数据*/
    @Override
    public void deleteFileData(List<String> ids, String userId) {
        //逻辑删除文件
        deleteFile(ids, userId);
        //逻辑删除相关数据
        deleteData(ids);
    }

    //逻辑删除文件
    @Transactional(rollbackFor = Exception.class)
    public void deleteFile(List<String> ids, String userId) {
        //逻辑删除文件
        String sql = "update qh_map_files set is_delete = '1' , update_time='" + PlatformDateUtils.getCurrentTimestamp() + "', update_user = '" + userId + "' where uuid in (:ids)";
        Map map = new HashMap();
        map.put("ids", ids);
        namedParameterJdbcTemplate.update(sql, map);
    }

    //逻辑删除相关数据
    @Transactional(rollbackFor = Exception.class)
    public void deleteData(List<String> ids) {
        //逻辑删除相关数据
        String sql = "update data_area set is_delete = '1' where fileuuid in (:ids)";
        Map map = new HashMap();
        map.put("ids", ids);
        namedParameterJdbcTemplate.update(sql, map);
    }

    //校验shp文件
    public String checkSHPFiles(String filePath, String province, String city, String area, String formatDate, String userID) {
        try {
            String returnMsg = "";
            System.out.println(new Date() + "-------------------1.开始readSHPFile");
            System.out.println(new Date() + "-------------------2.开始校验");
            //校验是否为2000坐标系
            if (!(checkCGCS2000(filePath))) {
                System.out.println(new Date() + "-----------校验失败.请上传正确的CGCS2000坐标系数据及.prj文件.");
                return "checkNotCGCS2000";
            }
            String cpgPath = filePath.substring(0, filePath.length() - 4) + ".cpg";
            String codeType = readCPG(cpgPath);//读取cpg文件编码
            //获取省市县所在区域字符串
            String boundariesCoordinate = getDistrictBoundaryCoordinate(province, city, area);
            //读取shp文件并校验--type上传类型（行政区划_）
            List<Object> list = readSHPFileCheck(filePath, codeType, "行政区划_", boundariesCoordinate, province, city, area);
            codeType = (String) list.get(0);//编码类型（0：UTF-8，1：GBK）
            int dataLength = (int) list.get(1);//数据长度
            String checkResult = (String) list.get(2);//校验结果
            //编码类型（0：UTF-8，1：GBK）
            if (codeType.equals("UTF-8")) {
                codeType = "0";
            } else {
                codeType = "1";
            }
            System.out.println(new Date() + "-------------------3.结束readSHPFile");
            System.out.println(new Date() + "-----------4.结束校验");
            if (checkResult.equals("校验成功")) {
                System.out.println(new Date() + "-------------------1.完成校验GeometryIsNotEqualsCoordinate");
                System.out.println(new Date() + "-------------------2.完成校验是否有乱码");
                System.out.println(new Date() + "-------------------3.完成校验字段空值");
                //System.out.println(new Date()+"-------------------4.完成校验是否为罗马数字");
                System.out.println(new Date() + "-----------校验成功.");
                String fileName = filePath.substring(filePath.lastIndexOf("/") + 1, filePath.length() - 4);
                //上传文件信息
                QhMapFilesEntity qhMapFilesEntity = new QhMapFilesEntity();
                qhMapFilesEntity.setUuid(UUIDGenerator.getUUID());
                qhMapFilesEntity.setFilepath(filePath);
                qhMapFilesEntity.setProvince(province);
                qhMapFilesEntity.setCity(city);
                qhMapFilesEntity.setArea(area);
                qhMapFilesEntity.setAffiliatedFileName(fileName);
                qhMapFilesEntity.setDateStr(formatDate);
                qhMapFilesEntity.setIsSave("0");
                qhMapFilesEntity.setIsDelete("0");
                qhMapFilesEntity.setType("行政区划_");//类型
                qhMapFilesEntity.setPostfix("shp");
                qhMapFilesEntity.setQualityStatus("1");//上传省市级类型（0：省，1：市）
                qhMapFilesEntity.setCodeType(codeType);//编码类型（0：UTF-8，1：GBK）
                qhMapFilesEntity.setDataLength(dataLength);//数据长度
                qhMapFilesEntity.setCreateUser(userID);//登录人
                System.out.println(new Date() + "-------------------4.开始保存");
                //保存到上传文件管理表
                saveMapFiles(qhMapFilesEntity);
                //根据类型保存到数据库
                returnMsg = saveQhMapFilesToDatabaseByType(qhMapFilesEntity);
                System.out.println(new Date() + "-------------------5.结束保存");
            } else {
                System.out.println(new Date() + "-----------校验失败." + checkResult);
                returnMsg = "上传文件中第"+(dataLength+1)+"行数据#" + checkResult;
            }
            //返回的消息
            return returnMsg;
        } catch (RuntimeException e) {
            log.error(e.getMessage(), e);
            return "插入或更新数据出现错误: <br/>" + e.getMessage();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return "数据导入失败, 服务器内部出现异常!";
        }
    }

    @Override
    public Integer countByCounty(String province, String city, String county) {
        StringBuilder sql = new StringBuilder(" select count(*) from data_area where province = '" + province + "' and city = '" + city + "' and county = '" + county + "' and is_delete = '0' ");
        return jdbcTemplate.queryForObject(sql.toString(), Integer.class);
    }

    @Override
    public Integer countByCity(String province, String city) {
        StringBuilder sql = new StringBuilder(" select count(*) from data_area where province = '" + province + "' and city = '" + city + "' and is_delete = '0' ");
        return jdbcTemplate.queryForObject(sql.toString(), Integer.class);
    }

    @Override
    public Integer countByProvince(String province) {
        StringBuilder sql = new StringBuilder(" select count(*) from data_area where province = '" + province + "' and is_delete = '0' ");
        return jdbcTemplate.queryForObject(sql.toString(), Integer.class);
    }

    @Override
    public List<String> getByCounty(String province, String city, String county) {
        String sql = String.format(" select street from data_area where province = '%s' and city = '%s' and county = '%s' and is_delete = '0'", province, city, county);
        return jdbcTemplate.queryForList(sql.toString(), String.class);
    }

    @Override
    public Integer countByProvinceAndYear(String provinceName, String taskYear) {
        return jdbcTemplate.queryForObject("SELECT count(t1.*) from data_area t1 LEFT JOIN qh_map_files t2 on t1.fileuuid = t2.uuid where t1.province = '' and (t2.update_time LIKE '' or t2.create_time LIKE '') and t2.is_delete = '0'", Integer.class, provinceName, "%" + taskYear+"%", "%" + taskYear+"%");
    }

    //根据类型保存到数据库
    public String saveQhMapFilesToDatabaseByType(QhMapFilesEntity qhMapFilesEntity) {
        String fileUuid = qhMapFilesEntity.getUuid();
        String type = qhMapFilesEntity.getType();
        String filePath = qhMapFilesEntity.getFilepath();
        String affiliatedFileName = qhMapFilesEntity.getAffiliatedFileName();
        String province = qhMapFilesEntity.getProvince();
        String city = qhMapFilesEntity.getCity();
        String area = qhMapFilesEntity.getArea();
        //String createUser  = qhMapFilesEntity.getCreateUser();
        String postfix = qhMapFilesEntity.getPostfix();//文件类型：shp | gdb
        String codeType = qhMapFilesEntity.getCodeType();//编码类型（0：UTF-8，1：GBK）
        int dataLength = qhMapFilesEntity.getDataLength();
        String createUser = qhMapFilesEntity.getCreateUser();//创建人
        String dateStr = qhMapFilesEntity.getDateStr();//日期
        if (codeType.equals("0")) {
            codeType = "UTF-8";
        } else {
            codeType = "GBK";
        }
        System.out.println(new Date() + "------开始导入." + affiliatedFileName + "----数据长度." + dataLength);
        //test
        /*if(dataLength>1000000){
            return "导入失败."+affiliatedFileName+"数据长度过大"+dataLength;
        }*/
        String resMsg = affiliatedFileName;//返回结果
        String result = "";
        try {
            //更新为正在保存状态
            updateSaveNowQhMapFile(qhMapFilesEntity);
            //根据日期和类型查询全部文件
            QhMapFilesQueryParams queryParams = new QhMapFilesQueryParams();
            queryParams.setType(type);//上传类型（行政区划_）
            //queryParams.setIsDelete("0");//未删除
            //queryParams.setIsSave("0");//未保存
            //queryParams.setProvince(province);
            //queryParams.setCity(city);
            //queryParams.setArea(area);
            queryParams.setDateStr(dateStr);//日期
            List<QhMapFilesEntity> list = searchQhMapFilesByParams(queryParams);
            //上传日期的所有文件数量
            int fileListCount = 0;
            if (list != null) {
                fileListCount = list.size();
            }
            //保存
            if (postfix.equals("shp")) {//保存shp文件
                result = newImportShapeFile(filePath, province, city, area, fileUuid, codeType, dataLength, createUser, dateStr, fileListCount);
            } else if (postfix.equals("gdb")) {//保存GDB文件
                //result = this.qhProbabilityEarthquakeDangerService.newImportGDBFile(filePath,province,city,area,createUser,codeType,dataLength);
            }
            //已保存成功
            if (result.contains("成功导入")) {
                /*if(list!=null && list.size()>0){
                    //批量更新为已删除状态
                    updateLogicDeleteQhMapFiles(list);
                }*/
                //更新为已保存状态
                updateSaveQhMapFile(qhMapFilesEntity);
                resMsg += "导入成功." + result + "当前数据所在文件UUID" + fileUuid;
            } else {
                resMsg += "导入失败." + result;
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        return resMsg;
    }

    //保存shp文件数据
    public String newImportShapeFile(String filePath, String province, String city, String area, String fileUuid, String codeType, int dataLength, String createUser, String dateStr, int fileListCount) {
        // 返回的消息
        StringBuilder returnMsg = new StringBuilder();
        try {
            System.out.println(new Date() + "-------------------1.开始保存");
            //保存--zyt
            int count = newSaveData(filePath, province, city, area, codeType, dataLength, fileUuid, createUser, dateStr, fileListCount);
            if (count == dataLength) {
                System.out.println(new Date() + "-------------------2.结束保存");
                returnMsg.append("成功导入" + count + "条数据.");
            } else {
                System.out.println(new Date() + "-------------------2.结束保存");
                returnMsg.append("导入出现异常，仅导入" + count + "条数据.");
            }
            return returnMsg.toString();
        } catch (RuntimeException e) {
            log.error(e.getMessage(), e);
            return "插入或更新数据出现错误: <br/>" + e.getMessage();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return "数据导入失败, 服务器内部出现异常!";
        }
    }

    //保存shp文件数据
    private int newSaveData(String filePath, String province, String city, String area, String codeType, int dataLength, String fileUuid, String createUser, String dateStr, int fileListCount) {
        int count = 0;
        int num = 5000;//每次保存的数据长度
        try {
            String prjPath = filePath.substring(0, filePath.length() - 4) + ".prj";
            String strWKTMercator = readPRJ(prjPath);
            if (strWKTMercator != "") setStrWKTMercator(strWKTMercator);
            System.out.println(new Date() + "-------------------1.开始readSHPFile");
            SimpleFeatureCollection colls = readShp(filePath, null, codeType);
            System.out.println(new Date() + "-------------------2.结束readSHPFile");
            List<AreaEntity> list = new ArrayList<>();
            int total = dataLength;
            boolean bool = false;//是否保存
            //开始时间
            Long begin = new Date().getTime();
            String lonLatStr = "", wkt = "";
            SimpleFeatureIterator iters = colls.features();
            while (iters.hasNext()) {
                count++;
                bool = false;//是否保存
                if (count < total) {
                    if (count % num == 0) {
                        bool = true;//是否保存
                        //开始时间
                        begin = new Date().getTime();
                    }
                } else {
                    bool = true;//是否保存
                }
                SimpleFeature sf = iters.next();
                List<Object> values = sf.getAttributes();
                //空间数据
                String geo = values.get(0).toString();

                //主键
                String areaId = UUIDGenerator.getUUID();
                int i = 1;
                //市
                String city1 = values.get(i++).toString();
                if (PlatformObjectUtils.isEmpty(city1)) {
                    city1 = city;//市
                }
                //区县
                String county = values.get(i++).toString();
                if (PlatformObjectUtils.isEmpty(county)) {
                    county = area;//区县
                }
                //街道、乡镇
                String street = values.get(i++).toString();
                //村、社区
                String village = "";
                if (values.get(4) != null) {
                    village = values.get(4).toString();
                }
                //状态0正常1删除
                String delFlag = "0";

                AreaEntity areaEntity = new AreaEntity();
                areaEntity.setAreaId(areaId);
                areaEntity.setStreet(street);
                areaEntity.setVillage(village);
                areaEntity.setIsDelete(delFlag);
                areaEntity.setProvince(province);
                areaEntity.setCity(city1);
                areaEntity.setCounty(county);
                areaEntity.setFileUuid(fileUuid);
                areaEntity.setGeomText(geo);
                list.add(areaEntity);
                if (bool) {
                    if (list != null && list.size() > 0) {
                        String sql = "insert into data_area " +
                                "(area_id,street,village,is_delete," +
                                "province,city,county,fileuuid,geom) " +
                                "values (:areaId,:street,:village,:isDelete," +
                                ":province,:city,:county,:fileUuid,st_geometryfromtext(:geomText,4490))";
                        namedParameterJdbcTemplate.batchUpdate(sql, SqlParameterSourceUtils.createBatch(list));
                    }
                    //结束时间
                    Long end = new Date().getTime();
                    //耗时
                    System.out.println(new Date() + "----count: " + count + ",cast : " + (end - begin) / 1000 + " s");
                    //清空
                    list.clear();
                }
            }
            iters.close();

        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("保存第" + count + "条数据出现异常!");
            //已保存的数量
            count = (int) Math.floor(count / num) * num;
        }

        return count;
    }

    //更新为正在保存状态
    @Transactional(rollbackFor = Exception.class)
    public int updateSaveNowQhMapFile(QhMapFilesEntity qhMapFilesEntity) throws Exception {
        List<QhMapFilesEntity> list = new ArrayList<QhMapFilesEntity>();
        list.add(qhMapFilesEntity);
        int count = qhMapFilesImport.sqlBatchUpdateNowEntities(list);

        return count;
    }

    //批量更新为已删除状态
    @Transactional(rollbackFor = Exception.class)
    public int updateLogicDeleteQhMapFiles(List<QhMapFilesEntity> list) throws Exception {
        int count = qhMapFilesImport.sqlBatchLogicDeleteEntities(list);

        return count;
    }

    //更新为已保存状态
    @Transactional(rollbackFor = Exception.class)
    public int updateSaveQhMapFile(QhMapFilesEntity qhMapFilesEntity) throws Exception {
        List<QhMapFilesEntity> list = new ArrayList<QhMapFilesEntity>();
        list.add(qhMapFilesEntity);
        int count = qhMapFilesImport.sqlBatchUpdateEntities(list);

        return count;
    }

    //根据参数查询文件
    public List<QhMapFilesEntity> searchQhMapFilesByParams(QhMapFilesQueryParams queryParams) {
        List<QhMapFilesEntity> list = qhMapFilesNativeRepository.searchMapFilesByJDBC(queryParams);

        return list;
    }

    //校验是否为2000坐标系
    public boolean checkCGCS2000(String path) {
        String prjPath = path.substring(0, path.length() - 4) + ".prj";
        String strWKTMercator = readPRJ(prjPath);
        if (strWKTMercator == "") return false;
        CoordinateReferenceSystem sourceTarget = null;
        try {
            sourceTarget = CRS.parseWKT(strWKTMercator);
        } catch (FactoryException e) {
            e.printStackTrace();
            System.out.println(path + ": 解析错误!");
        }
        String name = sourceTarget.getName().toString();
        if (name.equals("GCS_China_Geodetic_Coordinate_System_2000")) return true;
        return false;
    }

    //保存到上传文件管理表
    private void saveMapFiles(QhMapFilesEntity qhMapFilesEntity) throws Exception {
        List<QhMapFilesEntity> list = new ArrayList<QhMapFilesEntity>();
        list.add(qhMapFilesEntity);
        String affiliatedFileName = qhMapFilesEntity.getAffiliatedFileName();
        String province = qhMapFilesEntity.getProvince();
        String city = qhMapFilesEntity.getCity();
        String area = qhMapFilesEntity.getArea();
        //逻辑删除未保存的文件
        deleteMapFileByParams(affiliatedFileName, province, city, area);
        //保存
        qhMapFilesImport.sqlBatchSaveEntities(list);
    }

    //逻辑删除未保存的文件
    private void deleteMapFileByParams(String affiliatedFileName, String province, String city, String area) {
        //查询上传文件表
        QhMapFilesQueryParams qhMapFilesQueryParams = new QhMapFilesQueryParams();
        qhMapFilesQueryParams.setProvince(province);
        qhMapFilesQueryParams.setCity(city);
        qhMapFilesQueryParams.setArea(area);
        //qhMapFilesQueryParams.setAffiliatedFileName(affiliatedFileName);
        qhMapFilesQueryParams.setType("行政区划_");//上传类型（行政区划_）
        //查询文件（未删除）
        List<QhMapFilesEntity> list = qhMapFilesImport.searchMapFilesUnSaved(qhMapFilesQueryParams);
        if (!PlatformObjectUtils.isEmpty(list) && list.size() > 0) {
            //逻辑删--上传文件表
            qhMapFilesImport.sqlBatchLogicDeleteEntities(list);
        }
    }

    @Autowired
    private BoundaryNativeRepository boundaryNativeRepository;

    //获取省市县所在区域字符串
    public String getDistrictBoundaryCoordinate(String province, String city, String area) {
        String coordinate = "";
        return coordinate;
        /*BoundaryQueryParams queryParams = new BoundaryQueryParams();
        queryParams.setType("1");//1: 行政区划 2: 普查区划
        if(PlatformObjectUtils.isEmpty(area)){//市
            queryParams.setLevel("1");//0: 省 1: 市 2: 县
            queryParams.setName(city);
        }else{//县
            queryParams.setLevel("2");//0: 省 1: 市 2: 县
            queryParams.setName(area);
        }
        queryParams.setProvince(province);
        queryParams.setCity(city);
        queryParams.setArea(area);
        //查询省市县所在区域边界列表
        List<BoundaryEntity> boundaryEntities = this.boundaryNativeRepository.newListBoundaries(queryParams);
        if (boundaryEntities.size() == 1) {
            BoundaryEntity boundaryEntity = boundaryEntities.get(0);
            coordinate = boundaryEntity.getCoordinate();

        } else if (boundaryEntities.size() == 0) {
            System.out.println("NoDistrictBoundaryData");
        } else {
            System.out.println("DistrictBoundaryDataRedundance");
        }
        return coordinate;*/
    }

    //读取shp文件并校验--type上传类型（行政区划_）
    public List<Object> readSHPFileCheck(String path, String codeType, String type, String boundariesCoordinate,
                                         String province, String city, String county) {
        List<Object> result = new ArrayList<Object>();
        String prjPath = path.substring(0, path.length() - 4) + ".prj";
        String strWKTMercator = readPRJ(prjPath);
        if (strWKTMercator != "") setStrWKTMercator(strWKTMercator);
        String lonLatStr = "", wkt = "";
        SimpleFeatureCollection colls1 = readShp(path, null, codeType);
        SimpleFeatureIterator iters = colls1.features();
        String resMsg = "校验成功";
        int count = 0;
        //校验空间分辨率不是6秒
        double lon = 0, lat = 0;
        //List<String> allWktStrList = new ArrayList<String>();//全部空间信息字符串列表
        List<Double> allLonList = new ArrayList<Double>();
        List<Double> allLatList = new ArrayList<Double>();
        SimpleFeature sf = null;

        //校验矢量面是否在省市县所在区域内
        List<List<com.css.fxfzypg.modules.spatialData.repository.entity.Polygon>> multiPolygonList = new ArrayList<List<com.css.fxfzypg.modules.spatialData.repository.entity.Polygon>>();
        List<Geometry> multiPolygonGeometryList = new ArrayList<Geometry>();
        //Geometry boundariesGeometry = null;//行政区域
        //boundariesGeometry = getPolygonGeometryList(boundariesCoordinate);//行政区域
        List<com.css.fxfzypg.modules.spatialData.repository.entity.Point[]> boundaries = getDistrictBoundaryByString(boundariesCoordinate);
        //省市区县字符串列表--用于校验省市区县名称是否匹配
        List<String> provinceCityCountyList = new ArrayList<String>();

        while (iters.hasNext()) {
            if (count % 100000 == 0) {
                System.out.println(count);
            }
            sf = iters.next();
            List<Object> attributes = sf.getAttributes();
            //0.判断字段数量是否符合要求
            int size = attributes.size();
            if ("行政区划_".equals(type)) {
                if (size < 5) {
                    resMsg = "fieldNumError";
                    break;
                }
            }
            //校验矢量面是否在省市县所在区域内
            /*if("RLMPolygon_".equals(type)){
                //根据属性获取矢量面列表
                List<com.css.fxfzypg.modules.spatialData.repository.entity.Polygon> polygonList = getPolygonList(attributes);
                //校验数据是否在省市县所在区域边界内
                if(!newCheckPointIsInDistrict(boundaries, polygonList)){
                    resMsg = "PointIsNotInDistrict";
                    break;
                }

                //添加到面经纬度列表用于校验面是否相交
                multiPolygonList.add(polygonList);
                //test
                Geometry polygon = getPolygonGeometryList(attributes.get(0).toString());
                multiPolygonGeometryList.add(polygon);
            }*/
            if ("行政区划_".equals(type)) {
                //1.校验GeometryIsNotEqualsCoordinate
                String pointWkt = attributes.get(0).toString();
                /*String A = attributes.get(1).toString();//经度
                String B = attributes.get(2).toString();//纬度
                //新校验经纬度方法
                if (!newGeometryIsEqualsCoordinate(pointWkt, A, B)) {
                    resMsg = "GeometryIsNotEqualsCoordinate";
                    break;
                }*/

                /*//可注释判断以下判断点是否在行政区划内代码
                //判断点是否在行政区划内
                if(!newCheckPointIsInDistrictBoundary(boundaries,A,B)){
                    resMsg = "PointIsNotInDistrict";
                    break;
                }*/
                if (!pointWkt.contains("POLYGON")) {
                    resMsg = "空间数据类型错误，应为面数据";
                    break;
                }
            }
            //2.校验是否有乱码
            int msssyIndex = -1;
            //校验是否有乱码
            for (int j = 0; j < attributes.size(); j++) {
                if (attributes.get(j) == null) {
                    continue;
                }
                String value = attributes.get(j).toString();
                for (int k = 0; k < value.length() / 2; k++) {
                    char c = value.charAt(k);
                    // 当从Unicode编码向某个字符集转换时，如果在该字符集中没有对应的编码，则得到0x3f（即问号字符?）
                    //从其他字符集向Unicode编码转换时，如果这个二进制数在该字符集中没有标识任何的字符，则得到的结果是0xfffd
                    if ((int) c == 0xfffd) {
                        // 存在乱码
                        msssyIndex = count;
                        break;
                    }
                }
                if (msssyIndex != -1) {
                    resMsg = "messyCode";
                    break;
                }
            }
            if (msssyIndex != -1) {
                break;
            }
            //3.校验字段空值
            for (int j = 0; j < attributes.size(); j++) {
                //非必填
                if (j == 1) {//市
                    if (!PlatformObjectUtils.isEmpty(city)) {
                        continue;
                    }
                } else if (j == 2) {//区县
                    if (!PlatformObjectUtils.isEmpty(county)) {
                        continue;
                    }
                }
                if (j > 3) {
                    break;
                }
                if (attributes.get(j) == null) {
                    resMsg = "fieldNullValue";
                    break;
                }
                String value = attributes.get(j).toString();
                //校验字段空值
                if (value == null || "".equals(value.trim())) {
                    resMsg = "fieldNullValue";
                    break;
                }
            }
            if (!resMsg.equals("校验成功")) {
                break;
            }
            //上传类型（行政区划_）
            /*if ("行政区划_".equals(type)) {
                //4.校验空间分辨率不是6秒
                String A = attributes.get(1).toString();
                String B = attributes.get(2).toString();
                lon = Double.parseDouble(A);
                lat = Double.parseDouble(B);
                allLonList.add(lon);
                allLatList.add(lat);
                //校验是否空间位置重叠
                //allWktStrList.add(attributes.get(0).toString());
            }*/

            //4.校验数据内容是否符合规范
            if ("行政区划_".equals(type)) {
                //
            }

            //校验省市区县名称是否匹配
            boolean bool = true;
            String city1 = attributes.get(1).toString();
            String county1 = attributes.get(2).toString();
            if (PlatformObjectUtils.isEmpty(city1)) {
                city1 = city;
            } else {
                if (!PlatformObjectUtils.isEmpty(city)) {
                    if (!city1.equals(city)) {
                        bool = false;
                    }
                }
            }
            if (PlatformObjectUtils.isEmpty(county1)) {
                county1 = county;
            } else {
                if (!PlatformObjectUtils.isEmpty(county)) {
                    if (!county1.equals(county)) {
                        bool = false;
                    }
                }
            }
            String provinceCityCounty = province + "-" + city1 + "-" + county1;
            if (!provinceCityCountyList.contains(provinceCityCounty)) {
                provinceCityCountyList.add(provinceCityCounty);
                //校验省市区县名称是否匹配
                bool = checkProvinceCityCounty(province, city1, county1);
            }
            if (bool == false) {
                resMsg = "provinceCityCountyFormatError";
                break;
//                System.out.println(provinceCityCounty);
            }

            count++;
        }
        iters.close();
        System.out.println(count);

        //返回结果
        result.add(codeType);//编码类型（0：UTF-8，1：GBK）
        result.add(count);//数据长度
        result.add(resMsg);//校验结果
        //校验是否有乱码
        if (resMsg.indexOf("messyCode") != -1 && !codeType.equals("GBK")) {
            result = readSHPFileCheck(path, "GBK", type, boundariesCoordinate, province, city, county);
        }

        return result;
    }

    //读取cpg文件编码
    public String readCPG(String path) {
        String codeType = "UTF-8";
        StringBuffer result = new StringBuffer();
        File file = new File(path);
        if (!file.exists()) return "";
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(file));
            String tempString = null;
            while ((tempString = reader.readLine()) != null) {
                result.append(tempString);
            }
            reader.close();
            //返回结果
            codeType = result.toString();
            codeType = codeType.toUpperCase();//转换大写
        } catch (IOException e) {
            e.printStackTrace();
        }
        return codeType;
    }

    public String readPRJ(String path) {
        StringBuffer result = new StringBuffer();
        File file = new File(path);
        if (!file.exists()) return "";
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(file));
            String tempString = null;
            while ((tempString = reader.readLine()) != null) {
                result.append(tempString);
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result.toString();
    }

    public SimpleFeatureCollection readShp(String path, Filter filter, String codeType) {
        SimpleFeatureSource featureSource = readStoreByShp(path, codeType);
        if (featureSource == null) return null;
        try {
            return filter != null ? featureSource.getFeatures(filter) : featureSource.getFeatures();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public SimpleFeatureSource readStoreByShp(String path, String codeType) {
        File file = new File(path);
        FileDataStore store;
        SimpleFeatureSource featureSource = null;
        try {
            store = FileDataStoreFinder.getDataStore(file);
            ((ShapefileDataStore) store).setCharset(Charset.forName(codeType));
            featureSource = store.getFeatureSource();
            store.dispose();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return featureSource;
    }

    //获取省市县所在区域边界列表
    public List<com.css.fxfzypg.modules.spatialData.repository.entity.Point[]> getDistrictBoundaryByString(String coordinate) {
        List<com.css.fxfzypg.modules.spatialData.repository.entity.Point[]> boundaries = new ArrayList<>();
        if (coordinate == null || "".equals(coordinate)) {
            System.out.println("NoDistrictBoundaryData");
        } else {
            coordinate = coordinate.substring(coordinate.indexOf("(((") + 3, coordinate.lastIndexOf(")))"));
            coordinate = coordinate.replace(")), ((", "|");
            //coordinate = coordinate.replace("), (", "#");
            coordinate = coordinate.replace("), (", "|");
            String[] coordinates = StringUtils.split(coordinate, "|");
            for (int j = 0; j < coordinates.length; j++) {
                coordinates[j] = coordinates[j].replace(", ", ";");
                coordinates[j] = coordinates[j].replace(" ", ",");
                String[] lonlats = StringUtils.split(coordinates[j], ";");
                com.css.fxfzypg.modules.spatialData.repository.entity.Point[] points = new com.css.fxfzypg.modules.spatialData.repository.entity.Point[lonlats.length];
                for (int i = 0; i < lonlats.length; i++) {
                    String[] lonlat = StringUtils.split(lonlats[i], ",");
                    com.css.fxfzypg.modules.spatialData.repository.entity.Point point = new com.css.fxfzypg.modules.spatialData.repository.entity.Point();
                    point.x = Double.parseDouble(lonlat[0]);
                    point.y = Double.parseDouble(lonlat[1]);
                    points[i] = point;
                }
                boundaries.add(points);
            }
        }

        return boundaries;
    }

    public String reverseWktMultiPolygon(String wktPolygon) {
        String oldWkt = wktPolygon;
        oldWkt = oldWkt.substring(oldWkt.indexOf("(((") + 3, oldWkt.lastIndexOf(")))"));
        oldWkt = oldWkt.replace(")), ((", "|");
        oldWkt = oldWkt.replace("), (", "#");

        String wktPolygon1 = "";
        String[] polygon1 = StringUtils.split(oldWkt, "|");
        for (int i = 0; i < polygon1.length; i++) {
            if (polygon1[i].indexOf("#") != -1) {
                String[] polygon2 = StringUtils.split(polygon1[i], "#");
                for (int j = 0; j < polygon2.length; j++) {
                    String wktPolygon2 = "";
                    String[] coords = polygon2[j].split(", ");
                    for (int k = 0; k < coords.length; k++) {
                        String[] lonLat = coords[k].split(" ");
                        String lon = lonLat[1];
                        String lat = lonLat[0];
                        wktPolygon2 += lon + " " + lat + ", ";
                    }
                    wktPolygon1 += wktPolygon2.substring(0, wktPolygon2.length() - 2) + "), (";
                }
                wktPolygon1 = wktPolygon1.substring(0, wktPolygon1.length() - 4) + ")), ((";
            } else {
                String wktPolygon2 = "";
                String[] coords = polygon1[i].split(", ");
                for (int k = 0; k < coords.length; k++) {
                    String[] lonLat = coords[k].split(" ");
                    String lon = lonLat[1];
                    String lat = lonLat[0];
                    wktPolygon2 += lon + " " + lat + ", ";
                }
                wktPolygon1 += wktPolygon2.substring(0, wktPolygon2.length() - 2) + ")), ((";
            }
        }
        wktPolygon1 = wktPolygon1.substring(0, wktPolygon1.length() - 6);

        return "MULTIPOLYGON (((" + wktPolygon1 + ")))";
    }

    public String reverseWktPolygon(String wktPolygon) {
        String oldWkt = wktPolygon;
        oldWkt = oldWkt.substring(oldWkt.indexOf("(") + 2, oldWkt.lastIndexOf("))"));

        String polygonWkt = "Polygon (", coordinate = "";
        String sp = oldWkt.indexOf("),(") != -1 ? "),(" : (oldWkt.indexOf("), (") != -1 ? "), (" : "");
        if ("".equals(sp)) {
            coordinate = "(";
            String[] coordinates = oldWkt.split(",");
            for (int i = 0; i < coordinates.length; i++) {
                String[] coords = coordinates[i].split(" ");
                coordinate += coords[1] + " " + coords[0] + ",";
            }
            coordinate = coordinate.substring(0, coordinate.length() - 1) + ")";
            polygonWkt += coordinate + ")";
        } else {
            oldWkt = oldWkt.replace(sp, "#");
            sp = "#";
            String[] coordinates = oldWkt.split(sp);
            for (int i = 0; i < coordinates.length; i++) {
                coordinate = coordinates[i];
                String _coordinates = "(";
                String[] coords = coordinate.split(","), _coords = null;
                for (int j = 0; j < coords.length; j++) {
                    _coords = coords[j].split(" ");
                    _coordinates += _coords[1] + " " + _coords[0] + ",";
                }
                _coordinates = _coordinates.substring(0, _coordinates.length() - 1) + ")";
                polygonWkt += _coordinates + ",";
            }
            polygonWkt += polygonWkt.substring(0, polygonWkt.length() - 1) + ")";
        }
        return polygonWkt;
    }

    public String reverseWktPoint(String wktPoint) {
        String oldWkt = wktPoint;
        oldWkt = oldWkt.substring(oldWkt.indexOf("(") + 1, oldWkt.lastIndexOf(")"));
        String[] coords = oldWkt.split(" ");
        return "POINT (" + coords[1] + " " + coords[0] + ")";
    }

    public String reverseWktMultiPoint(String wktMultiPoint) {
        String oldWkt = wktMultiPoint;
        oldWkt = oldWkt.substring(oldWkt.indexOf("(") + 2, oldWkt.lastIndexOf(")") - 1);
        String sp = oldWkt.indexOf("),(") != -1 ? "),(" : (oldWkt.indexOf("), (") != -1 ? "), (" : "");
        String[] coordinates = StringUtils.split(oldWkt, sp);
        String newWkt = "MULTIPOINT ((", coordinate = "";
        String[] coords = null;
        for (int i = 0; i < coordinates.length; i++) {
            coordinate = coordinates[i];
            coords = coordinate.split(" ");
            //newWkt += "(" + coords[1] + " " + coords[0] + "),";
            newWkt += coords[1] + " " + coords[0] + ",";
        }
        newWkt = newWkt.substring(0, newWkt.length() - 1) + "))";
        return newWkt;
    }

    //根据属性获取boundary.Point数组列表
    public List<com.css.fxfzypg.modules.spatialData.repository.entity.Polygon> getPolygonList(List<Object> attributes) {
        List<com.css.fxfzypg.modules.spatialData.repository.entity.Point> pointArray0 = null;//面点数组
        List<List<com.css.fxfzypg.modules.spatialData.repository.entity.Point>> noPointList = null;//镂空的面点数组列表
        List<com.css.fxfzypg.modules.spatialData.repository.entity.Point> pointArray = null;
        com.css.fxfzypg.modules.spatialData.repository.entity.Point point = null;
        List<com.css.fxfzypg.modules.spatialData.repository.entity.Polygon> polygonList = new ArrayList<com.css.fxfzypg.modules.spatialData.repository.entity.Polygon>();
        com.css.fxfzypg.modules.spatialData.repository.entity.Polygon polygon = null;

        String coordinates = attributes.get(0).toString();
        try {
            if (coordinates.indexOf("MULTIPOLYGON") != -1) {
                coordinates = coordinates.substring(coordinates.indexOf("(((") + 3, coordinates.lastIndexOf(")))"));
                if (coordinates.indexOf(")), ((") != -1) {//多个面
                    coordinates = coordinates.replace(")), ((", "|");
                    coordinates = coordinates.replace("), (", "#");
                    String[] geometries = StringUtils.split(coordinates, "|");
                    for (int j = 0; j < geometries.length; j++) {
                        String geometry = geometries[j];
                        //获取面
                        polygon = new com.css.fxfzypg.modules.spatialData.repository.entity.Polygon(geometry);
                        polygonList.add(polygon);
                    }

                } else if (coordinates.indexOf("), (") != -1) {//单个面（包括镂空的面）
                    coordinates = coordinates.replace("), (", "#");
                    //获取面
                    polygon = new com.css.fxfzypg.modules.spatialData.repository.entity.Polygon(coordinates);
                    polygonList.add(polygon);

                } else {//单个面
                    //获取面
                    polygon = new com.css.fxfzypg.modules.spatialData.repository.entity.Polygon(coordinates);
                    polygonList.add(polygon);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            //System.out.println("矢量面："+attributes.get(0).toString());
        }

        return polygonList;
    }

    //根据属性获取矢量面Geometry
    public Geometry getPolygonGeometryList(String coordinates) {
        Geometry geometry = null;
        try {
            GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(null);
            WKTReader reader = new WKTReader(geometryFactory);
            geometry = reader.read(coordinates);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return geometry;
    }

    public boolean newGeometryIsEqualsCoordinate(String wkt, String lon, String lat) {
        String wktPart = "";
        if (wkt.toLowerCase().indexOf("multipoint") != -1) {
            wktPart = wkt.substring(wkt.indexOf("(") + 2, wkt.lastIndexOf(")") - 1);
        } else if (wkt.toLowerCase().indexOf("point") != -1) {
            wktPart = wkt.substring(wkt.indexOf("(") + 1, wkt.lastIndexOf(")"));
        }

        int det = 1 + 8;//保留8位小数判断
        String[] array = wktPart.split(" ");
        String longitude = array[0], latitude = array[1];
        String newWktLongitudeStr = newKeepDecimalDigits(longitude, det), newWktLatitudeStr = newKeepDecimalDigits(latitude, det);
        String newLongitudeStr = newKeepDecimalDigits(lon, det), newLatitudeStr = newKeepDecimalDigits(lat, det);

        double newWktLongitude = Double.parseDouble(newWktLongitudeStr), newWktLatitude = Double.parseDouble(newWktLatitudeStr);
        double newLongitude = Double.parseDouble(newLongitudeStr), newLatitude = Double.parseDouble(newLatitudeStr);

        //if (newWktLongitude == newLongitude && newWktLatitude == newLatitude) return true;
        //判断是否在10-6次方内
        double tempLon = Math.abs(newWktLongitude - newLongitude);
        double tempLat = Math.abs(newWktLatitude - newLatitude);
        if (tempLon < 0.000001 && tempLat < 0.000001) {
            return true;
        }

        //判断保留8位（不四舍五入）属性字段经纬度与geometry是否一致
        if (getGeometryIsEqualsCoordinateBool(longitude, latitude, lon, lat, det)) return true;

        return false;
    }

    private String newKeepDecimalDigits(String floatStr, int det) {
        int index = floatStr.indexOf("."), len = floatStr.length();
        if (index == -1) return floatStr;
        int temp = det + 1;
        String tempfloatPart = floatStr.substring(index + 1, (len > (index + temp)) ? (index + temp) : len);
        String floatPart = floatStr.substring(index + 1, (len > (index + det)) ? (index + det) : len);

        boolean bool = false;//判断是否四舍五入
        int findex = 0;
        String sindex = "";
        if (tempfloatPart.length() > floatPart.length()) {
            if (tempfloatPart.startsWith(floatPart) && (tempfloatPart.endsWith("9") || tempfloatPart.endsWith("8") || tempfloatPart.endsWith("7") || tempfloatPart.endsWith("6") || tempfloatPart.endsWith("5"))) {
                for (int i = floatPart.length() - 1; i >= 0; i--) {
                    String subStr = floatPart.substring(i, i + 1);
                    if (subStr.equals("9")) {
                        continue;
                    }
                    findex = i;
                    sindex = Integer.toString(Integer.parseInt(subStr) + 1);
                    break;
                }
                floatPart = floatPart.substring(0, findex) + sindex;
                bool = true;
            }
        }

        String newFloatStr = floatStr.substring(0, index) + "." + floatPart;
        if (bool && sindex.equals("")) {//floatPart都是9
            newFloatStr = Integer.toString(Integer.parseInt(floatStr.substring(0, index)) + 1);
        }

        return newFloatStr;
    }

    //保留8位（不四舍五入）
    private String newKeepDecimalDigits2(String floatStr, int det) {
        int index = floatStr.indexOf("."), len = floatStr.length();
        if (index == -1) return floatStr;
        String floatPart = floatStr.substring(index + 1, (len > (index + det)) ? (index + det) : len);
        String newFloatStr = floatStr.substring(0, index) + "." + floatPart;

        return newFloatStr;
    }

    //判断保留8位（不四舍五入）属性字段经纬度与geometry是否一致
    private boolean getGeometryIsEqualsCoordinateBool(String longitude, String latitude, String lon, String lat, int det) {
        boolean bool = false;
        String newWktLongitudeStr = newKeepDecimalDigits2(longitude, det), newWktLatitudeStr = newKeepDecimalDigits2(latitude, det);
        String newLongitudeStr = newKeepDecimalDigits2(lon, det), newLatitudeStr = newKeepDecimalDigits2(lat, det);

        double newWktLongitude = Double.parseDouble(newWktLongitudeStr), newWktLatitude = Double.parseDouble(newWktLatitudeStr);
        double newLongitude = Double.parseDouble(newLongitudeStr), newLatitude = Double.parseDouble(newLatitudeStr);

        //if (newWktLongitude == newLongitude && newWktLatitude == newLatitude) bool= true;
        //判断是否在10-6次方内
        double tempLon = Math.abs(newWktLongitude - newLongitude);
        double tempLat = Math.abs(newWktLatitude - newLatitude);
        if (tempLon < 0.000001 && tempLat < 0.000001) {
            bool = true;
        }

        return bool;
    }

    //截取8位小数（不四舍五入）
    public String getNewDecimalDigits(String floatStr) {
        int det = 1 + 8;
        int index = floatStr.indexOf("."), len = floatStr.length();
        if (index == -1) return floatStr;
        String floatPart = floatStr.substring(index + 1, (len > (index + det)) ? (index + det) : len);
        String newFloatStr = floatStr.substring(0, index) + "." + floatPart;

        return newFloatStr;
    }

    //地球半径,单位 km
    private double EARTH_RADIUS = 6378.137;

    //根据经纬度，计算两点间的距离
    public double getDistance(double longitude1, double latitude1, double longitude2, double latitude2) {
        // 纬度
        double lat1 = Math.toRadians(latitude1);
        double lat2 = Math.toRadians(latitude2);
        // 经度
        double lng1 = Math.toRadians(longitude1);
        double lng2 = Math.toRadians(longitude2);
        // 纬度之差
        double a = lat1 - lat2;
        // 经度之差
        double b = lng1 - lng2;
        // 计算两点距离的公式
        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
                Math.cos(lat1) * Math.cos(lat2) * Math.pow(Math.sin(b / 2), 2)));
        // 弧长乘地球半径, 返回单位: 千米
        s = s * EARTH_RADIUS;
        return s;
    }

    //判断6秒距离200
    public boolean isLessSixSecondDistance(List<Double> allLonList, List<Double> allLatList) {
        for (int i = 0; i < allLonList.size(); i++) {
            if (i > 100) {//只判断100个点
                break;
            }
            double lng1 = allLonList.get(i);
            double lat1 = allLatList.get(i);
            boolean bool = false;
            double minDistance = -1;//最小距离
            for (int j = 0; j < allLonList.size(); j++) {
                if (j == i) {
                    continue;
                }
                double lng2 = allLonList.get(j);
                double lat2 = allLatList.get(j);
                double distance = getDistance(lng1, lat1, lng2, lat2);
                if (minDistance == -1 || distance < minDistance) {
                    minDistance = distance;
                }
                if (distance < 0.25) {//250米
                    bool = true;
                    break;
                }
            }
            if (bool == false) {
                System.out.println("第" + i + "条数据判断6秒距离不在250米内：" + minDistance + "km--minDistance");
                System.out.println("第" + i + "条数据经纬度：" + lng1 + "," + lat1);
                return false;
            }
        }

        return true;
    }

    //校验矢量面是否在存在单要素自相交
    public String checkIsPolygonsIntersect(List<List<com.css.fxfzypg.modules.spatialData.repository.entity.Polygon>> multiPolygonList) {
        String resultStr = "校验成功";
        com.css.fxfzypg.modules.spatialData.repository.entity.Polygon polygon = null;
        com.css.fxfzypg.modules.spatialData.repository.entity.Polygon polygon1 = null;
        List<com.css.fxfzypg.modules.spatialData.repository.entity.Polygon> polygonList = null;
        List<com.css.fxfzypg.modules.spatialData.repository.entity.Polygon> allPolygonList = null;//全部面列表
        if (multiPolygonList != null && multiPolygonList.size() > 0) {
            allPolygonList = new ArrayList<com.css.fxfzypg.modules.spatialData.repository.entity.Polygon>();
            for (int n = 0; n < multiPolygonList.size(); n++) {
                polygonList = multiPolygonList.get(n);
                for (int i = 0; i < polygonList.size(); i++) {
                    allPolygonList.add(polygonList.get(i));
                }
            }
        }
        if (allPolygonList != null && allPolygonList.size() > 0) {
            for (int i = 0; i < allPolygonList.size(); i++) {
                polygon = allPolygonList.get(i);
                //判断矢量面是否存在自相交
                if (checkIsPolygonSelfIntersect(polygon)) {
                    resultStr = "isPolygonSelfIntersect";
                    String temp = "面自相交";
                    System.out.println(temp);
                    break;
                }
            }
        }

        return resultStr;
    }

    //判断矢量面是否存在自相交
    private boolean checkIsPolygonSelfIntersect(com.css.fxfzypg.modules.spatialData.repository.entity.Polygon polygon) {
        boolean bool = false;//不存在自相交
        int flag = 0;
        List<com.css.fxfzypg.modules.spatialData.repository.entity.Point> points = polygon.points;
        for (int i = 0; i < (points.size() - 1); i++) { //循环开始元素
            for (int j = i + 1; j < points.size(); j++) { //循环后续所有元素
                //如果相等，则重复
                if (points.get(i).x == points.get(j).x && points.get(i).y == points.get(j).y) {
                    flag++; //设置标志变量为重复
                }
            }
        }
        if (flag > 1) {//除首尾点外存在重复的点
            bool = true;//存在自相交
        }

        return bool;
    }

    private double GLOBAL_THRESH = 1E-6;

    //校验矢量面是否在存在两两重叠或相交（或单要素自相交）
    public String checkIsPolygonGeometrysIntersect(List<Geometry> multiPolygonGeometryList) {
        String resultStr = "校验成功";
        Geometry geometry1 = null;
        Geometry geometry2 = null;
        List<com.css.fxfzypg.modules.spatialData.repository.entity.Polygon> polygonList = null;
        if (multiPolygonGeometryList != null && multiPolygonGeometryList.size() > 0) {
            for (int i = 0; i < multiPolygonGeometryList.size(); i++) {
                geometry1 = multiPolygonGeometryList.get(i);
                //Geometry geometry1IntersectGeometry1 = geometry1.intersection(geometry1);
                //判断是否存在两两重叠或相交
                for (int j = i + 1; j < multiPolygonGeometryList.size(); j++) {
                    geometry2 = multiPolygonGeometryList.get(j);
                    //自相交
                    //Geometry geometry2IntersectGeometry2 = geometry2.intersection(geometry2);
                    //Geometry geometry1IntersectGeometry2 = geometry1IntersectGeometry1.intersection(geometry2IntersectGeometry2);
                    //double area = geometry1IntersectGeometry2.getArea();
                    //两两相交
                    Geometry geometry1IntersectGeometry2 = geometry1.intersection(geometry2);
                    double area = geometry1IntersectGeometry2.getArea();
                    if (area >= GLOBAL_THRESH) {
                        resultStr = "isPolygonsIntersect";
                        String temp = "存在两两重叠或相交";
                        //temp += "，面："+geometry1.toString();
                        //temp += "相交于面："+geometry2.toString();
                        temp += "，相交面积：" + area;
                        System.out.println(temp);
                        break;
                    }
                }
                if (resultStr != "校验成功") {
                    break;
                }
            }
        }

        return resultStr;
    }

    //校验矢量面数据是否在省市县所在区域边界内
    public boolean newCheckPointIsInDistrict(List<com.css.fxfzypg.modules.spatialData.repository.entity.Point[]> boundaries, List<com.css.fxfzypg.modules.spatialData.repository.entity.Polygon> polygonList) {
        com.css.fxfzypg.modules.spatialData.repository.entity.Point point = null;
        List<com.css.fxfzypg.modules.spatialData.repository.entity.Point> pointArray = null;
        com.css.fxfzypg.modules.spatialData.repository.entity.Point[] boundary = null;
        com.css.fxfzypg.modules.spatialData.repository.entity.Polygon polygon = null;

        if (boundaries != null && boundaries.size() > 0 && polygonList != null && polygonList.size() > 0) {
            for (int i = 0; i < polygonList.size(); i++) {
                boolean bool = false;
                polygon = polygonList.get(i);
                pointArray = polygon.points;
                if (pointArray != null && pointArray.size() > 0) {
                    for (int j = 0; j < pointArray.size(); j++) {
                        point = pointArray.get(j);
                        bool = false;
                        double minDis = Double.MAX_VALUE;
                        for (int k = 0; k < boundaries.size(); k++) {
                            boundary = boundaries.get(k);
                            if (AreaBoundaryUtil.isPointInPolygon(point, boundary)) {
                                bool = true;
                                break;
                            } else {//判断容差距离
                                //double minDis = Double.MAX_VALUE;
                                for (int n = 0; n < boundary.length - 1; n++) {
                                    com.css.fxfzypg.modules.spatialData.repository.entity.Point p1 = boundary[n], p2 = boundary[n + 1];
                                    double d = AreaBoundaryUtil.pointToLine(p1.x, p1.y, p2.x, p2.y, point.x, point.y);
                                    if (minDis > d) minDis = d;
                                }
                                if (minDis < GLOBAL_THRESH) {
                                    bool = true;
                                    break;
                                }
                            }
                        }
                        if (bool == false) {
                            String temp = "矢量面上的点：" + point;
                            temp += "--------不在行政区划范围内----minDis:" + minDis;
                            System.out.println(temp);
                            return false;
                        }
                    }
                }
            }
        } else {
            System.out.println("无行政区划范围----");
            return false;
        }

        return true;
    }

    //校验点数据是否在省市县所在区域边界内
    public boolean newCheckPointIsInDistrictBoundary(List<com.css.fxfzypg.modules.spatialData.repository.entity.Point[]> boundaries, String lonStr, String latStr) {
        com.css.fxfzypg.modules.spatialData.repository.entity.Point point = new com.css.fxfzypg.modules.spatialData.repository.entity.Point(Double.parseDouble(lonStr), Double.parseDouble(latStr));
        com.css.fxfzypg.modules.spatialData.repository.entity.Point[] boundary = null;
        boolean bool = false;
        if (boundaries != null && boundaries.size() > 0) {
            for (int k = 0; k < boundaries.size(); k++) {
                boundary = boundaries.get(k);
                if (AreaBoundaryUtil.isPointInPolygon(point, boundary)) {
                    bool = true;
                    break;
                } else {//判断容差距离
                    double minDis = Double.MAX_VALUE;
                    for (int n = 0; n < boundary.length - 1; n++) {
                        com.css.fxfzypg.modules.spatialData.repository.entity.Point p1 = boundary[n], p2 = boundary[n + 1];
                        double d = AreaBoundaryUtil.pointToLine(p1.x, p1.y, p2.x, p2.y, point.x, point.y);
                        if (minDis > d) minDis = d;
                    }
                    if (minDis < GLOBAL_THRESH) {
                        bool = true;
                        break;
                    }
                }
            }
            if (bool == false) {
                String temp = "点：" + point + "--------不在行政区划范围内----";
                System.out.println(temp);
                return false;
            }
        } else {
            System.out.println("无行政区划范围----");
            return false;
        }

        return true;
    }

    private String strWKTMercator = "PROJCS[\"CGCS2000_GK_Zone_20\",GEOGCS[\"GCS_China_Geodetic_Coordinate_System_2000\",DATUM[\"D_China_2000\",SPHEROID[\"CGCS2000\",6378137.0,298.257222101]],PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]],PROJECTION[\"Gauss_Kruger\"],PARAMETER[\"False_Easting\",20500000.0],PARAMETER[\"False_Northing\",0.0],PARAMETER[\"Central_Meridian\",117.0],PARAMETER[\"Scale_Factor\",1.0],PARAMETER[\"Latitude_Of_Origin\",0.0],UNIT[\"Meter\",1.0]]";

    public void setStrWKTMercator(String wKTMercator) {
        strWKTMercator = wKTMercator;
    }

    public String wkt2lonLat(String wktPolygon) {
        Geometry geomtry = null;
        try {
            GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(null);
            WKTReader reader = new WKTReader(geometryFactory);
            geomtry = reader.read(wktPolygon);
            geomtry = webMercator2lonLat(geomtry);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        if (geomtry != null)
            return geomtry.toString();
        else return null;
    }

    public Geometry webMercator2lonLat(Geometry geom) {
        try {
            CoordinateReferenceSystem sourceTarget = CRS.parseWKT(strWKTMercator);
            CoordinateReferenceSystem crsTarget = CRS.decode("EPSG:4490");
            MathTransform transform = CRS.findMathTransform(sourceTarget, crsTarget, true);
            //MathTransform transform = CRS.findMathTransform(sourceTarget, DefaultGeographicCRS.WGS84, true);
            return JTS.transform(geom, transform);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    //获取重点活动ID（11位）
    public String getZdhdId(String dateStr, int fileListCount) {
        String zdhdId = dateStr;
        fileListCount = fileListCount - 1;//从0开始
        if (fileListCount < 10) {
            zdhdId += "00" + fileListCount;
        } else if (fileListCount < 100) {
            zdhdId += "0" + fileListCount;
        } else if (fileListCount < 1000) {
            zdhdId += String.valueOf(fileListCount);
        }

        return zdhdId;
    }

    //获取流水码（5位)
    public String getTempCountNum(int count) {
        count = count - 1;//从0开始
        //流水码（5位）
        String tempCountNum = "00000";
        if (count < 10) {
            tempCountNum = "0000" + count;
        } else if (count < 100) {
            tempCountNum = "000" + count;
        } else if (count < 1000) {
            tempCountNum = "00" + count;
        } else if (count < 10000) {
            tempCountNum = "0" + count;
        } else if (count < 100000) {
            tempCountNum = String.valueOf(count);
        } else {//超过5位
            tempCountNum = String.valueOf(count);
        }

        return tempCountNum;
    }

    //判断字符串是否为整数或者小数（大于0）
    public static boolean isNumericFloat(String str) {
        Pattern pattern = Pattern.compile("[0-9]*\\.?[0-9]+");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        float temp = Float.parseFloat(str);
        if (temp > 0) {
            return true;
        } else {
            return false;
        }
    }

    //校验省市区县名称是否匹配
    public Boolean checkProvinceCityCounty(String province, String city, String county) {
        Boolean bool = false;
        try {
            //判断省市县的名称是否符合规范
            String divisionIds = sysAreaService.getIdByCondition(URLEncoder.encode(province, "utf-8"),
                    URLEncoder.encode(city, "utf-8"),
                    URLEncoder.encode(county, "utf-8"));
            if (!PlatformObjectUtils.isEmpty(divisionIds)) {
                int length = divisionIds.split("_").length;
                if (length == 3) {
                    bool = true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return bool;
    }

    @Override
    public List<String> getAllByTaskDirtrict(String geom) {
        String sql = "select street from data_area where ST_Intersects(st_astext(geom),'"+geom+"')";
        return jdbcTemplate.queryForList(sql, String.class);
    }
}
